import java.awt.AWTException;
import java.awt.Cursor;
import java.awt.Image;
import java.awt.Point;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.IOException;
import java.net.URL;
import java.nio.DoubleBuffer;
import java.nio.IntBuffer;

import javax.media.opengl.DebugGL;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCanvas;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.glu.GLU;
import javax.swing.JFrame;

import org.junit.Test;

import com.sun.opengl.util.FPSAnimator;
import com.sun.opengl.util.GLUT;
import static org.junit.Assert.*;

public class MyJoglCanvas extends GLCanvas implements GLEventListener,
KeyListener, MouseListener, MouseMotionListener {
	
	/**
	 * 
	 */
    float brightness = 1.10f,mouse_sensivity = 10f,motion_blur = 4f;
	private static final long serialVersionUID = 1L;
	private FPSAnimator animator;
	private GLU glu;
//	private AL al;
	private Robot r;
	private GLUT glut;
	private Camera player;
	private Point ptrMousePosition;
	private Point curMousePosition;
	private Whater whater;
	private Grid grid;
	public static Boat[] boat;
	public static Vector3D[] list_of_targets;
	public static int current_target = 0,shooting_result = 0,enemy_shooting_result = 0,terminated = 0,enemy_terminated = 0;
	private Clouds cloud;
	private Sockets socket;
	private Rocket rocket;
	private Tree tree;
	private Map map;
	private Grass grass;
	private Explosion explode;
	private char[] buffer;
	private int load_num;
	private int buffer_num,frames_after_release;
	public static int number_of_editing_boat = 0,max_boat = 10,variable = -10;
	public static boolean editing_boats = true,render_scene;
	private boolean chat,release, fire,choose_target,letter_input,number_input,boom,screen_draw = true,center_known = false,grid_draw = true,but_3 = false;
	private boolean map_draw = false;
	private int s_width,s_height,center_x,center_y,armed_units = 20;
	public static int player_field=1,cur_field = 1;
	private int[] shadowMap = new int[1];
	private Ground ground;
	private Screen screen;
	private Atmosphere atmo;
	private float start_time,cur_time ,e_getx=0f,e_gety=0f;
	private float mv[],pr[];
	public static float FPS,perspective = 45,radius = 0.83f,blur = 0.2f;
	private int frames,shadowMapSize = 512;
	public static boolean start_firing = false, ready_for_war = false,enemy_ready = false;
	public static Vector3D target;
	private JFrame frame2;
	public static float fps() {
		return FPS;
	}
	public MyJoglCanvas() {}
	public MyJoglCanvas(int width, int height, GLCapabilities capabilities, JFrame frame) {
//		super(capabilities);
//        setSize(width, height);
    	ptrMousePosition = new Point();
    	curMousePosition = new Point();
        addGLEventListener(this);
        addKeyListener(this);
        addMouseListener(this);
        addMouseMotionListener(this);
        frame2 = frame;
        boat = new Boat[max_boat];
        load_num = 0;
        render_scene = false;
        list_of_targets = new Vector3D[20];
        for(int i = 0; i < 20; i++) list_of_targets[i] = new Vector3D();
	}
	private char[] init_string(char string[]) {
		string[0] = 'f';
		string[1] = 'p';
		string[2] = 's';
		string[3] = '=';
		frames++;
		if(frames == 10) {
			if((cur_time - start_time) > 0)  FPS = 1f/((cur_time - start_time) / 10000f);
			start_time = System.currentTimeMillis()%10000;
			cur_time = System.currentTimeMillis()%10000;
			frames = 0;
		}
		string[4] = (char)((int)FPS/10 + (int)'0');
		string[5] = (char)((int)(FPS%10) + (int)'0');
		string[6] = '.';
		string[7] = (char)((int)(FPS*10)%10 + (int)'0');
		string[8] = '\0';
		return string;
	}
	private char[] init_string_load(char string[]) {
		string[0] = 'l';
		string[1] = 'o';
		string[2] = 'a';
		string[3] = 'd';
		string[4] = 'i';
		string[5] = 'n';
		string[6] = 'g';
		string[7] = ' ';
		string[8] = (char)((int)(load_num*4.5f+1)/10 + (int)'0');
		string[9] = (char)((int)((load_num*4.5f+1)%10) + (int)'0');
		string[10] = '%';
		string[11] = '\0';
		return string;
	}
	private void renderFPS(int x, int y, GLAutoDrawable drawable) {

		{
			final GL gl = drawable.getGL();
			char string[] = new char[9];
			init_string(string);
		        //Assume we are in MODEL_VIEW already
			gl.glPushMatrix();
			gl.glLoadIdentity();
			gl.glMatrixMode(GL.GL_PROJECTION);
			gl.glPushMatrix();
			gl.glLoadIdentity();
			java.nio.IntBuffer viewport;
			viewport = IntBuffer.allocate(4);
			gl.glGetIntegerv(GL.GL_VIEWPORT, viewport);
			int view[] = new int[4];
			view = viewport.array();
			glu.gluOrtho2D(0,view[2],view[3],0);
			gl.glDepthFunc(GL.GL_ALWAYS);
			gl.glActiveTexture(GL.GL_TEXTURE0);
			gl.glDisable(GL.GL_TEXTURE_2D);
			gl.glColor3f (1,1,1);
			gl.glRasterPos2f(x, y);
			for (int i = 0; string[i]!= '\0'; ++i)
		    glut.glutBitmapCharacter(GLUT.BITMAP_HELVETICA_18, string[i]);
			gl.glDepthFunc(GL.GL_LESS);
			gl.glPopMatrix();
			gl.glMatrixMode(GL.GL_MODELVIEW);
			gl.glPopMatrix();
		}
	}
	
	private void renderload(int x, int y, GLAutoDrawable drawable) {

		{
			final GL gl = drawable.getGL();
			char string[] = new char[20];
			init_string_load(string);
		        //Assume we are in MODEL_VIEW already
			gl.glPushMatrix();
			gl.glLoadIdentity();
			gl.glMatrixMode(GL.GL_PROJECTION);
			gl.glPushMatrix();
			gl.glLoadIdentity();
			java.nio.IntBuffer viewport;
			viewport = IntBuffer.allocate(4);
			gl.glGetIntegerv(GL.GL_VIEWPORT, viewport);
			int view[] = new int[4];
			view = viewport.array();
			glu.gluOrtho2D(0,view[2],view[3],0);
			gl.glDepthFunc(GL.GL_ALWAYS);
			gl.glActiveTexture(GL.GL_TEXTURE0);
			gl.glDisable(GL.GL_TEXTURE_2D);
			gl.glColor3f (1,1,1);
			gl.glRasterPos2f(x, y);
			for (int i = 0; string[i]!= '\0'; ++i)
		    glut.glutBitmapCharacter(GLUT.BITMAP_HELVETICA_18, string[i]);
			gl.glDepthFunc(GL.GL_LESS);
			gl.glPopMatrix();
			gl.glMatrixMode(GL.GL_MODELVIEW);
			gl.glPopMatrix();
		}
	}
		private void prereleasing_chat(GLAutoDrawable drawable) {

			{
				final GL gl = drawable.getGL();
				char string[] = new char[5];
				string[0] = 's';
				string[1] = 'a';
				string[2] = 'y';
				string[3] = ':';
				string[4] = '\0';
				//init_string(string);
			        //Assume we are in MODEL_VIEW already
				gl.glPushMatrix();
				gl.glLoadIdentity();
				gl.glMatrixMode(GL.GL_PROJECTION);
				gl.glPushMatrix();
				gl.glLoadIdentity();
				java.nio.IntBuffer viewport;
				viewport = IntBuffer.allocate(4);
				gl.glGetIntegerv(GL.GL_VIEWPORT, viewport);
				int view[] = new int[4];
				view = viewport.array();
				glu.gluOrtho2D(0,view[2],view[3],0);
				gl.glDepthFunc(GL.GL_ALWAYS);
				gl.glActiveTexture(GL.GL_TEXTURE0);
				gl.glDisable(GL.GL_TEXTURE_2D);
				gl.glColor3f (1,1,1);
				gl.glRasterPos2f(20, 40);
				for (int i = 0; string[i]!= '\0'; ++i)
			    glut.glutBitmapCharacter(GLUT.BITMAP_HELVETICA_18, string[i]);
				
				gl.glRasterPos2f(60, 40);
				for (int i = 0; i < buffer_num; ++i)
			    glut.glutBitmapCharacter(GLUT.BITMAP_HELVETICA_18, buffer[i]);
				gl.glDepthFunc(GL.GL_LESS);
				gl.glPopMatrix();
				gl.glMatrixMode(GL.GL_MODELVIEW);
				gl.glPopMatrix();
			}
	}
	private void setCamera(GL gl, GLU glu) {
        // Change to projection matrix.
        gl.glMatrixMode(GL.GL_PROJECTION);
        gl.glLoadIdentity();
      //  al.alListener3f(AL.AL_POSITION, Camera.pos.x, Camera.pos.y, Camera.pos.z);
     //   al.alListener3i(AL.AL_VELOCITY,0,0,0);
        float[] oriLis = new float[] {(float) (Camera.pos.x()+Math.cos(player.yaw)*Math.cos(player.pitch)),
                (float) (Camera.pos.y()+Math.sin(player.yaw)*Math.cos(player.pitch)),
                (float) (Camera.pos.z()+Math.sin(player.pitch)),0.0f,0.0f,1.0f};
     //   al.alListenerfv(AL.AL_ORIENTATION, oriLis, 0);
        // Perspective.
        float widthHeightRatio = (float) getWidth() / (float) getHeight();
        glu.gluPerspective(perspective, widthHeightRatio, 0.1, 10000.0);
        //glu.gluLookAt(0, 0, distance, 0, 0, 0, 0, 1, 0);
        glu.gluLookAt(Camera.pos.x(),Camera.pos.y(),Camera.pos.z(),
                Camera.pos.x()+Math.cos(player.yaw)*Math.cos(player.pitch),
                Camera.pos.y()+Math.sin(player.yaw)*Math.cos(player.pitch),
                Camera.pos.z()+Math.sin(player.pitch),
                0,0,1);

        // Change back to model view matrix.
        gl.glMatrixMode(GL.GL_MODELVIEW);
        gl.glLoadIdentity();
    }
	private void init_shadow_map(GL gl, GLU glu) {
		 shadowMap[0] = Ground.get_shadow();
	}
    public void init(GLAutoDrawable drawable) {
    	try {
			r = new Robot();
		} catch (AWTException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	e_getx = 0;
    	e_gety = 0;
    //	ALut.alutInit();
    //	al = ALFactory.getAL();
    //	al.alGetError();
    	glu = new GLU();
    	glut = new GLUT();
    	start_time = System.currentTimeMillis()%10000;
    	cur_time = System.currentTimeMillis()%10000;
    	frames = 0;
    	mv = new float[16];
    	pr = new float[16];
    	buffer_num = 0;
    	frames_after_release = 0;
    	chat = false; release = false; choose_target = false;letter_input = false;number_input = false;
    	buffer = new char[100];
    	for(int i = 0; i < 10; i++) buffer[i] = 1;
    	final GL gl = drawable.getGL();
        drawable.setGL(new DebugGL(gl));
        fire = false;
        boom = false;
        target = new Vector3D(0,250,0);
        // Global settings.
        gl.glEnable(GL.GL_DEPTH_TEST);
        gl.glEnable(GL.GL_CULL_FACE);
        gl.glDepthFunc(GL.GL_LEQUAL);
        gl.glShadeModel(GL.GL_SMOOTH);
        gl.glEnable(GL.GL_MULTISAMPLE);
        gl.glHint(GL.GL_MULTISAMPLE_FILTER_HINT_NV, GL.GL_NICEST);//не работает нихера
        gl.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST);
        gl.glEnable(GL.GL_POLYGON_SMOOTH);
        gl.glHint(GL.GL_POLYGON_SMOOTH_HINT,GL.GL_NICEST);
        gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
        gl.glClearDepth(1.0f);
        animator = new FPSAnimator(this, 999);
        animator.start();
        atmo = new Atmosphere(gl, glu);
    	player=new Camera();
		screen = new Screen(gl, glu);
		socket = new Sockets(gl, glu, glut);
		
		
        //choosing server/client
        
    }
    
    
    void	renderToShadowMap (GL gl, GLU glu,int num_map)
    {
    	gl.glEnable        ( GL.GL_POLYGON_OFFSET_FILL );
    	gl.glPolygonOffset ( 4, 4 );

    	gl.glClear    ( GL.GL_DEPTH_BUFFER_BIT );
    	atmo.draw(player, 0);// now render scene from light position
    	gl.glMatrixMode   ( GL.GL_PROJECTION );
    	gl.glLoadIdentity ();

    	 float widthHeightRatio = (float) getWidth() / (float) getHeight();
         glu.gluPerspective(60.0f, widthHeightRatio, 400.0, 1000.0);
    	if(num_map == 1) glu.gluLookAt      ( Atmosphere.sun.x/3f, Atmosphere.sun.y/3f+3f, Atmosphere.sun.z/3f+3f,		// eye
    					 0, 0, 0,	// center
    					 0, 0, 1 );						// up
    	if(num_map == 2) glu.gluLookAt      ( Atmosphere.sun.x/3f, Atmosphere.sun.y/3f-3f, Atmosphere.sun.z/3f+3f,		// eye
				 0, 0, 0,	// center
				 0, 0, 1 );						// up
    	if(num_map == 3) glu.gluLookAt      ( Atmosphere.sun.x/3f, Atmosphere.sun.y/3f-3f, Atmosphere.sun.z/3f-3f,		// eye
				 0, 0, 0,	// center
				 0, 0, 1 );						// up
    	if(num_map == 4) glu.gluLookAt      ( Atmosphere.sun.x/3f, Atmosphere.sun.y/3f+3f, Atmosphere.sun.z/3f-3f,		// eye
				 0, 0, 0,	// center
				 0, 0, 1 );						// up

    	gl.glMatrixMode   ( GL.GL_MODELVIEW );
    	gl.glLoadIdentity ();
    	gl.glGetFloatv (  GL.GL_MODELVIEW_MATRIX,  mv ,0);
    	gl.glGetFloatv (  GL.GL_PROJECTION_MATRIX, pr ,0);
                                            // get modelview and projections matrices


    		
    	gl.glEnable         (  GL.GL_TEXTURE_2D );

 
        ground.draw(Camera.pos,player.yaw,player.pitch,true);
        //whater.draw(player2, getHeight(),getWidth(),1);
      //  grid.draw();
        //grass.draw(player2,0);
        tree.draw(Camera.pos);
        tree.draw_leaves(Camera.pos,cloud,player.yaw, player.pitch, 0,true);
      //  boom = rocket.draw(player2,fire,false,target);
     //   explode.draw(player2, boom, 0,target);

    										// copy depth map into texture
        ground.shot(getWidth(),getHeight(),num_map);
//    										// restore state
    	gl.glDisable        (  GL.GL_POLYGON_OFFSET_FILL );
    	gl.glColorMask      ( true,true,true,true);
    	
//    	
    	gl.glMatrixMode   ( GL.GL_MODELVIEW );
    	gl.glPushMatrix   ();

										// set correct texcoord transform
    	gl.glMatrixMode  ( GL.GL_TEXTURE );
    	gl.glPushMatrix  ();
//
    	gl.glLoadIdentity ();
////        glTranslatef   ( 0.5, 0.5, 0.5 );     // remap from [-1,1]^2 to [0,1]^2
////        glScalef       ( 0.5, 0.5, 0.5 );
    	gl.glMultMatrixf  ( pr,0 );
    	gl.glMultMatrixf  ( mv,0 );
//
//    	gl.glActiveTexture (GL.GL_TEXTURE0);
    }

    public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
    	GL gl = drawable.getGL();
        gl.glViewport(0, 0, width, height);
        s_width = width;
        s_height = height;
    }
    private void mouse_movement() {
    	float nSca=1;

    	e_gety = curMousePosition.y;
    	e_getx = curMousePosition.x;
    	//System.out.println(curMousePosition.x);
    	curMousePosition.setLocation(curMousePosition.x+(ptrMousePosition.x-curMousePosition.x)/motion_blur, curMousePosition.y+(ptrMousePosition.y-curMousePosition.y)/motion_blur);        
    	player.pitch -= mouse_sensivity/nSca*(float)(e_gety-curMousePosition.getY())/(float)getHeight();
        player.yaw -= mouse_sensivity/nSca*(float)(e_getx-curMousePosition.getX())/(float)getWidth();


        if( player.pitch>1.57) player.pitch=1.57f;
        if( player.pitch<-1.57) player.pitch=-1.57f;
    }
    private void loading(GL gl, GLU glu) {

        //player.pos.setXYZ(0f, 0f, 3f);
    	if(load_num > 22) return;
    	if(socket.server) {
    		player_field = 1;
    	}
    	else player_field = 2;
    	switch(load_num) {
    		case 0 :
    			whater=new Whater(gl, glu);
    			break;
    		case 1 :
    			explode = new Explosion(gl, glu);
    			break;
    		case 2 :
    			grid=new Grid(gl, glu);
    			break;
    		case 3 :
    			boat[0]=new Boat(gl, glu, 4,new Vector3D(20,24,0));
    			break;
    		case 4:
    			boat[1]=new Boat(gl, glu, 3,new Vector3D(20,20,0));
    			break;
    		case 5:
    			boat[2]=new Boat(gl, glu, 3,new Vector3D(20,20,0));
    			break;
    		case 6:
    			boat[3]=new Boat(gl, glu, 2,new Vector3D(20,24,0));
    			break;
    		case 7:
    			boat[4]=new Boat(gl, glu, 2,new Vector3D(20,24,0));
    			break;
    		case 8:
    			boat[5]=new Boat(gl, glu, 2,new Vector3D(20,24,0));
    			break;
    		case 9:
    			boat[6]=new Boat(gl, glu, 1,new Vector3D(20,20,0));
    			break;
    		case 10:
    			boat[7]=new Boat(gl, glu, 1,new Vector3D(20,20,0));
    			break;
    		case 11:
    			boat[8]=new Boat(gl, glu, 1,new Vector3D(20,20,0));
    			break;
    		case 12:
    			boat[9]=new Boat(gl, glu, 1,new Vector3D(20,20,0));
    			break;
    		case 13:
    			map = new Map(gl, glu);
    			break;
    		case 14:
    			cloud = new Clouds(gl, glu);
    			break;
    		case 15:
    			tree = new Tree(gl, glu);
    			break;
    		case 16:
    			ground = new Ground(gl, glu);
    			break;
    		case 17:
    			rocket = new Rocket(gl, glu);
    			break;
    		case 18:
    			grass = new Grass(gl,glu);
    			break;
    		case 19:
    			// cut
    			break;
    		case 20:
    			//cut
    			break;
    		case 21:
        // 	Start animator (which should be a field).
    			init_shadow_map(gl,glu);    
       // frame2.setSize(1000, 1000);
    		//  reshape(drawable, 0,0,1000,1000);
    			renderToShadowMap (gl, glu,1);
    			renderToShadowMap (gl, glu,2);
    			renderToShadowMap (gl, glu,3);
    			renderToShadowMap (gl, glu,4);
    			break;
    		case 22:
    			frame2.setExtendedState(JFrame.MAXIMIZED_BOTH);
    			Toolkit toolkit = Toolkit.getDefaultToolkit();
    			Image image = null;
    			URL imageURL= this.getClass().getResource(
    					"cursor.png");
    			image = toolkit.getImage(imageURL);
    			Point hotspot = new Point(0,0);
    			Cursor cursor = toolkit.createCustomCursor(image, hotspot, "Stone");
    			frame2.setCursor(cursor);
    			System.out.println("7/8 - brightness \n9/0 - zoom \ne - switch screen effects\n");
    			r.mouseMove(300, 300);
    			render_scene = true;
    			screen_draw = false;
    			cur_field = player_field;
    			player_field = 1;
    			break;
    		default :
    			break;
    		}
    		load_num++;
    }
    public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {}
    

    public void display(GLAutoDrawable drawable) {
    	//System.out.println("Variable = " + variable);
    	if(render_scene) mouse_movement();
    	if(socket == null) {
    		final GL gl = drawable.getGL();
            drawable.setGL(new DebugGL(gl));
    		socket = new Sockets(gl, glu, glut);
    	}
    	if(!release) frames_after_release++;
    	else frames_after_release = 0;
    	cur_time = System.currentTimeMillis()%10000;
    	if (!animator.isAnimating()) {
            return;
        }
        final GL gl = drawable.getGL();

        // Clear screen.
        if(render_scene)  player.cameraRun();
        //RENDER SHADOW MAP

        gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT);
               // Set camera.
        
         setCamera(gl, glu);
         socket.do_something();
         
         if(screen_draw && !render_scene) screen.draw(player,(float)getWidth(),(float)getHeight(),radius,brightness,false);
         if(!but_3) {
        if(release) prereleasing_chat(drawable);
        if(socket.but_2 && !release && buffer_num > 0){
        	socket.ready = true;
        	buffer_num = 0;				//отправка данных клиента об айпи сервера только после окончания ввода
        }
        if(!socket.connection) {
        	socket.choose_mode(drawable,s_width, s_height,buffer);
        	if(socket.connection) {
        		buffer_num = 0;								//очистка всех буферов обмена после установки соединения
        		buffer[0] = '\0';
        	}
        }
        if(!socket.connection) {
        	if(socket.but_2) {
        		release = true; //начало приема данных об айпи в случае выбора клиента
        	}
        	return;
        }
         }
        if(!render_scene) loading(gl,glu);
        
        if(render_scene) {
        	boolean tmp = false;
        	gl.glScalef(1f, 1f, -1f);//rotate scene to make reflection
        	DoubleBuffer clip_plane = null;
        	clip_plane = DoubleBuffer.allocate(4);
        	clip_plane.put(0,0);
        	clip_plane.put(1,0);
        	clip_plane.put(2,1);
        	clip_plane.put(3,0);
        	gl.glClipPlane(GL.GL_CLIP_PLANE0, clip_plane);
        	gl.glEnable(GL.GL_CLIP_PLANE0);//при построении отражения отсекается все что за зеркалом
        	gl.glCullFace(GL.GL_FRONT); //также отражаются задние грани
        	atmo.draw(player,FPS);
        	Atmosphere.sun.z *= -1f; //источник света также переворачивается
        	if(grid_draw) grid.draw();
        	for(int i = 0; i <= number_of_editing_boat;i++) {
        		boolean edit = false;
        		if(i == number_of_editing_boat && editing_boats) edit = true;
        		boat[i].draw(player,edit);
        		}
        	ground.draw(Camera.pos,player.yaw,player.pitch,true);
        	tree.draw(Camera.pos);
        	tree.draw_leaves(Camera.pos,cloud,player.yaw, player.pitch, 1,false);
        	if(MyJoglCanvas.player_field == 2)target.y += 8f;
        	boom = rocket.draw(player ,fire,true,target);
        	if(MyJoglCanvas.player_field == 2)target.y -= 8f;
        	if(fire) {
        		int result = 0;
        		for(int i = 0; i < 10; i++) {
        			int temp = boat[i].try_to_kill(target);
        			if(temp > 0) {
        				result = temp;
        				break;
      //dafuq
        			}
        		}	
        		shooting_result = result;
        		if(result != 0) armed_units--;
        	}
        	if(armed_units == 0) terminated = 1;

        	if(boom) {
        		start_firing = false;
        		if(shooting_result == 1 || enemy_shooting_result == 1) {
        			System.out.println("Target injured");
        			Screen.draw_info = 1;
        			Screen.frames_after_draw = 0;
        		}
        		else if(shooting_result == 2 || enemy_shooting_result == 2) {
        			System.out.println("Target terminated");
        			Screen.draw_info = 2;
        			Screen.frames_after_draw = 0;
        		}
        		else {
        			System.out.println("No injured targets");
            		if(player_field == 1) player_field = 2;
            		else player_field = 1;
            		Screen.draw_info = 3;
        			Screen.frames_after_draw = 0;
                	
        		}
        		if(terminated == 1 || enemy_terminated == 1) {
            		Screen.draw_info = 4;
            		Screen.frames_after_draw = 0;
            	}
        	}
        	if(Screen.draw_info == 4 && Screen.frames_after_draw >= 50) System.exit(0);
        	tmp = boom;
        	explode.draw(player, boom, 1,target);
        	Atmosphere.sun.z *= -1f;
        	gl.glCullFace(GL.GL_BACK);		 
        	gl.glDisable(GL.GL_CLIP_PLANE0);
        	whater.draw(player, getHeight(),getWidth(),0);
        	
        	gl.glScalef(1f, 1f, -1f);
        	
        	gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT | GL.GL_STENCIL_BUFFER_BIT);
     //   	gl.glDepthMask(true);
        	atmo.draw(player,FPS);     
        	for(int i = 0; i <= number_of_editing_boat;i++) {
        		boolean edit = false;
        		if(i == number_of_editing_boat && editing_boats) edit = true;
        		boat[i].draw(player,edit);
        		}
        	ground.draw(Camera.pos,player.yaw,player.pitch,false);
        	whater.draw(player, getHeight(),getWidth(),1);
        	if(grid_draw) grid.draw();
        	grass.draw(player,0);
        	tree.draw(Camera.pos);
        	tree.draw_leaves(Camera.pos,cloud,player.yaw, player.pitch, 0,false);
        	if(MyJoglCanvas.player_field == 2) target.y += 8f;
        	boom = rocket.draw(player,fire,false,target);
        	if(MyJoglCanvas.player_field == 2) target.y -= 8f;
        	explode.draw(player, boom, 0,target);
        	tree.draw_leaves(Camera.pos,cloud,player.yaw, player.pitch, 0,true);
        	screen.shot(getWidth(),getHeight());
        	if(map_draw)map.draw(player,(float)getWidth(),(float)getHeight(),radius);
        	if(screen_draw) screen.draw(player,(float)getWidth(),(float)getHeight(),radius,brightness,tmp);
        }
        
        if(render_scene) {
        	if(fire) fire = false;
        	if(boom) {
        		if(player_field == 1) player_field = 2;
        		else player_field = 1;
        		boom = false;
        	}
        	renderFPS(20,20,drawable);
        	if(choose_target) prereleasing_chat(drawable);//drawing what you are writing
        }	
        if(!render_scene) {
        	renderload(getWidth()/2-50,getHeight()/2,drawable);
        }
        if(!but_3) {
        try {
        	if(chat) buffer_num = 0;
        	if(frames_after_release == 300) {
        		buffer[0] = '\0';
        		chat = true;
        	}
			socket.writeMessage(drawable, chat,buffer);
			fire = start_firing;
			start_firing = false;
			chat = false;
		
		} catch (IOException e) {
			//System.out.println("NO FUCKING CHAT");
			socket.clear();
			socket = null;
			System.exit(0);
		}
        }
        }
    public void makeBuffer(KeyEvent e) {
    	if(buffer_num == 99 || e.getKeyCode() == KeyEvent.VK_ENTER) {
    		buffer[buffer_num] = '\0';
    		release = false;
    		chat = true;
    		return;
    	}
    	if(e.getKeyCode() == KeyEvent.VK_A) {
    		buffer[buffer_num] = 'a';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_1) {
    		buffer[buffer_num] = '1';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_2) {
    		buffer[buffer_num] = '2';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_3) {
    		buffer[buffer_num] = '3';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_4) {
    		buffer[buffer_num] = '4';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_5) {
    		buffer[buffer_num] = '5';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_6) {
    		buffer[buffer_num] = '6';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_7) {
    		buffer[buffer_num] = '7';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_8) {
    		buffer[buffer_num] = '8';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_9) {
    		buffer[buffer_num] = '9';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_0) {
    		buffer[buffer_num] = '0';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_B) {
    		buffer[buffer_num] = 'b';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_C) {
    		buffer[buffer_num] = 'c';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_D) {
    		buffer[buffer_num] = 'd';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_E) {
    		buffer[buffer_num] = 'e';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_F) {
    		buffer[buffer_num] = 'f';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_G) {
    		buffer[buffer_num] = 'g';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_H) {
    		buffer[buffer_num] = 'h';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_I) {
    		buffer[buffer_num] = 'i';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_J) {
    		buffer[buffer_num] = 'j';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_K) {
    		buffer[buffer_num] = 'k';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_L) {
    		buffer[buffer_num] = 'l';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_M) {
    		buffer[buffer_num] = 'm';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_N) {
    		buffer[buffer_num] = 'n';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_O) {
    		buffer[buffer_num] = 'o';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_P) {
    		buffer[buffer_num] = 'p';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_Q) {
    		buffer[buffer_num] = 'q';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_R) {
    		buffer[buffer_num] = 'r';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_S) {
    		buffer[buffer_num] = 's';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_T) {
    		buffer[buffer_num] = 't';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_U) {
    		buffer[buffer_num] = 'u';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_V) {
    		buffer[buffer_num] = 'v';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_W) {
    		buffer[buffer_num] = 'w';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_X) {
    		buffer[buffer_num] = 'x';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_Y) {
    		buffer[buffer_num] = 'y';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_Z) {
    		buffer[buffer_num] = 'z';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_SPACE) {
    		buffer[buffer_num] = ' ';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_COMMA) {
    		buffer[buffer_num] = ',';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_DECIMAL) {
    		buffer[buffer_num] = '.';
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_BACK_SPACE) {
    		if(buffer_num == 0) return;
    		else {
    			buffer_num--;
    			buffer[buffer_num] = '\0';
    			return;
    		}
    	}
    	else return;
    	buffer_num++;
        }
    
    public void make_target(KeyEvent e) {
    	float offset = 1f;//field
    	if(MyJoglCanvas.player_field == 1) offset = 161f;
    	float offset2 = 4;
    	if(buffer_num == 2 && e.getKeyCode() == KeyEvent.VK_ENTER) {
			buffer[buffer_num] = '\0';
			buffer_num = 0;
			choose_target = false;
			if(number_input && letter_input) {
				fire = true;
				start_firing = true;
			}
			number_input = false;
			letter_input = false;
			return;
    	}
    	if(buffer_num == 2) return;
    	if(e.getKeyCode() == KeyEvent.VK_A) {
    		buffer[buffer_num] = 'a';
    		target.y = offset;
    		letter_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_1) {
    		buffer[buffer_num] = '1';
    		target.x = 8 + offset2;
    		number_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_2) {
    		buffer[buffer_num] = '2';
    		target.x = 16 + offset2;
    		number_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_3) {
    		buffer[buffer_num] = '3';
    		target.x = 24 + offset2;
    		number_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_4) {
    		buffer[buffer_num] = '4';
    		target.x = 32 + offset2;
    		number_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_5) {
    		buffer[buffer_num] = '5';
    		target.x = 40 + offset2;
    		number_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_6) {
    		buffer[buffer_num] = '6';
    		target.x = 48 + offset2;
    		number_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_7) {
    		buffer[buffer_num] = '7';
    		target.x = 56 + offset2;
    		number_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_8) {
    		buffer[buffer_num] = '8';
    		target.x = 64 + offset2;
    		number_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_9) {
    		buffer[buffer_num] = '9';
    		target.x = 72 + offset2;
    		number_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_0) {
    		buffer[buffer_num] = '0';
    		target.x = offset2;
    		number_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_B) {
    		buffer[buffer_num] = 'b';
    		target.y = 8 + offset;
    		letter_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_C) {
    		buffer[buffer_num] = 'c';
    		target.y = 16 + offset;
    		letter_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_D) {
    		buffer[buffer_num] = 'd';
    		target.y = 24 + offset;
    		letter_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_E) {
    		buffer[buffer_num] = 'e';
    		target.y = 32 + offset;
    		letter_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_F) {
    		buffer[buffer_num] = 'f';
    		target.y = 40 + offset;
    		letter_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_G) {
    		buffer[buffer_num] = 'g';
    		target.y = 48 + offset;
    		letter_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_H) {
    		buffer[buffer_num] = 'h';
    		target.y = 56 + offset;
    		letter_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_I) {
    		buffer[buffer_num] = 'i';
    		target.y = 64 + offset;
    		letter_input = true;
    	}
    	else if(e.getKeyCode() == KeyEvent.VK_J) {
    		buffer[buffer_num] = 'j';
    		target.y = 72 + offset;
    		letter_input = true;
    	}
    	else return;
    	if(buffer_num < 2) buffer_num++;
    }
    public void keyPressed(KeyEvent e) {
    	if(release && !but_3) {
    		makeBuffer(e);
    		return;
    	}
    	if(choose_target) {
    		make_target(e);
    		return;
    	}
            if(e.getKeyCode() == KeyEvent.VK_W) {
                player.gow=true;
            }
            if(e.getKeyCode() == KeyEvent.VK_S) {
                player.gos=true;
            }
            if(e.getKeyCode() == KeyEvent.VK_A) {
                player.goa=true;
            }
            if(e.getKeyCode() == KeyEvent.VK_D) {
                player.god=true;
            }
            if(e.getKeyCode() == KeyEvent.VK_ESCAPE) {//THERE IS NO ESCAPE :C
                System.exit(0);
            }
            if(!render_scene) {
            if(e.getKeyCode() == KeyEvent.VK_1) {
                socket.but_1=true;
            }
            if(e.getKeyCode() == KeyEvent.VK_2) {
                socket.but_2=true;
            }
            if(e.getKeyCode() == KeyEvent.VK_3 && !socket.but_1 && !socket.but_2) {
                but_3 = true;
            }
            }
            if(e.getKeyCode() == KeyEvent.VK_Y) {
                release=true;
            }
            if(e.getKeyCode() == KeyEvent.VK_SPACE && !editing_boats && enemy_ready && player_field == cur_field) {
                choose_target=true;
            }
            if(e.getKeyCode() == KeyEvent.VK_9) {
            	radius += 0.005f;
            	if(radius > 2f) radius = 2f;
            }
            if(e.getKeyCode() == KeyEvent.VK_0) {
            	radius -= 0.005f;
            	if(radius < 0.83f) radius = 0.83f;
            }
            if(e.getKeyCode() == KeyEvent.VK_E) {
            	if(screen_draw) screen_draw = false;
            	else screen_draw = true;
            }
            if(e.getKeyCode() == KeyEvent.VK_6) {
            	variable ++;
            }
            if(e.getKeyCode() == KeyEvent.VK_7) {
            	brightness += 0.01f;
            	if(brightness > 2f) brightness = 2f;
            }
            if(e.getKeyCode() == KeyEvent.VK_8) {
            	brightness -= 0.01f;
            	if(brightness < 0.5f) brightness = 0.5f;
            }
            if(e.getKeyCode() == KeyEvent.VK_SHIFT) {
                Camera.PLAYER_SPEED*=3.0f;
            }
            if(e.getKeyCode() == KeyEvent.VK_L) {
                center_known = false;
            }
            if(e.getKeyCode() == KeyEvent.VK_M) {
                map_draw = true;
            }
            if(e.getKeyCode() == KeyEvent.VK_X) {
                if(grid_draw) grid_draw = false;
                else grid_draw = true;
            }
            if(e.getKeyCode() == KeyEvent.VK_R && editing_boats) {
                boat[number_of_editing_boat].rotate();
            }
            if(e.getKeyCode() == KeyEvent.VK_UP && editing_boats) {
                boat[number_of_editing_boat].move_to(new Vector3D(8,0,0));
            }
            if(e.getKeyCode() == KeyEvent.VK_DOWN && editing_boats) {
                boat[number_of_editing_boat].move_to(new Vector3D(-8,0,0));
            }
            if(e.getKeyCode() == KeyEvent.VK_LEFT && editing_boats) {
                boat[number_of_editing_boat].move_to(new Vector3D(0,8,0));
            }
            if(e.getKeyCode() == KeyEvent.VK_RIGHT && editing_boats) {
                boat[number_of_editing_boat].move_to(new Vector3D(0,-8,0));
            }
            if(e.getKeyCode() == KeyEvent.VK_ENTER && editing_boats) {
            	if(boat[number_of_editing_boat].in_ships());
            	else if(number_of_editing_boat == max_boat - 1) {
            		editing_boats = false;
            		ready_for_war = true;
            	}
            	else number_of_editing_boat++;
                
            }
    }
 
    public void keyReleased(KeyEvent e) {
    	if(e.getKeyCode() == KeyEvent.VK_W) {
            player.gow=false;
        }
        if(e.getKeyCode() == KeyEvent.VK_S) {
            player.gos=false;
        }
        if(e.getKeyCode() == KeyEvent.VK_A) {
            player.goa=false;
        }
        if(e.getKeyCode() == KeyEvent.VK_D) {
            player.god=false;
        }
        if(e.getKeyCode() == KeyEvent.VK_B) {
            fire=true;
        }
        if(e.getKeyCode() == KeyEvent.VK_SHIFT) {
            Camera.PLAYER_SPEED/=3.0f;
        }
        if(e.getKeyCode() == KeyEvent.VK_M) {
            map_draw = false;
        }
    }
 
    public void keyTyped(KeyEvent e) {}
    
    public void mousePressed(MouseEvent e){
    	if(!center_known && render_scene) {
    	r.mouseMove(300,300);
    	r.delay(0);
    //	System.out.println("after"+ e.getPoint().x+ " " +e.getPoint().y);
        center_x = e.getX();
        center_y = e.getY();
        center_known = true;
    	}
    }
    
    //public void mouseReleased(MouseEvent e){}

    public void mouseDragged(MouseEvent e){

    	//System.out.println("I move mouse, and when i press");

        

    }
    
    public void mouseMoved(MouseEvent e) {
    	if(render_scene) {
    //	ptrMousePosition.setLocation(getWidth() - e.getPoint().x,getHeight() - e.getPoint().y);
        ptrMousePosition.setLocation(ptrMousePosition.x +  (center_x - e.getPoint().x), ptrMousePosition.y + (center_y - e.getPoint().y));
    //    System.out.println("pointer "+ ptrMousePosition.x+ " " +ptrMousePosition.y + " screen " + curMousePosition.x+ " " +curMousePosition.y);
        r.mouseMove(300,300);
        r.delay(10);//move cursor to center
        if(!center_known) {
        	r.mousePress(InputEvent.BUTTON1_MASK);
        	r.mouseRelease(InputEvent.BUTTON1_MASK);
        }
        mouse_movement();
    	}
    }
    public void mouseClicked(MouseEvent e) {}
    public void mouseEntered(MouseEvent e) {}
    public void mouseExited(MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {}
}
